package de.herberlin.pss.action;

import java.io.File;

import org.apache.log4j.Logger;

import de.herberlin.pss.ServiceCallback;
import de.herberlin.pss.ServiceLocator;
import de.herberlin.pss.model.Directory;

public class PopulateDirAction implements Action {

	private File file=null;
	private Logger logger=Logger.getLogger(getClass());
	
	public PopulateDirAction(File pssFile) {
		this.file=pssFile;
	}
	
	public void perform(){
		if (file  != null) {
			String parentPath=file.getParent();
			if (parentPath != null) {
				if (parentPath.startsWith("/")) {
					parentPath=parentPath.substring(1);
				}
				String[] parts=parentPath.split(File.separator);
				try {
					storeParts(parts);
				} catch (Exception e) {
					logger.error(e,e);
					rollback();
				}
			}
		}
	}
	
	private void storeParts(String[] parts) throws Exception {
		
		ServiceCallback callback=new ServiceCallback(ServiceLocator.getSqliteFile().getPath());
		callback.getResult("delete from "+new Directory().getTableName());
		for (int i=0;i<parts.length;i++) {
			Directory dir=new Directory();
			dir.set(Directory.Key.iDirId, (i+1)+"");
			dir.set(Directory.Key.cDirName, parts[i]);
			dir.set(Directory.Key.iParentDirId, (i)+"");
			callback.getResult(dir.createInsertQuery());
			
		}
	}

	public void rollback() {
	}

}
